"use server"


import {Client} from "dwolla-v2";




const getEnvironment = (): "production" | "sandbox" => {

    const environment = process.env.DWOLLA_ENV as string;

    switch (environment) {
        case "sandbox":
            return "sandbox";
        case "production":
            return "production";
        default:
            throw new Error(
                "Dwolla 环境应该设置为 `sandbox` or `production`"
            );
    }
};

const dwollaClient = new Client({
    environment: getEnvironment(),
    key: process.env.DWOLLA_KEY as string,
    secret: process.env.DWOLLA_SECRET as string,
});

export const createDwollaCustomer = async (
    newCustomer: NewDwollaCustomerParams
) => {
    try {
        return await dwollaClient
            .post("customers", newCustomer)
            .then((res) => res.headers.get("location"));
    } catch (err) {
        console.error("创建客户失败: ", err);
    }
};

export const createOnDemandAuthorization = async () => {
    try {
        const onDemandAuthorization = await dwollaClient.post(
            "on-demand-authorizations"
        );
        const authLink = onDemandAuthorization.body._links;
        return authLink;
    } catch (err) {
        console.error("Creating an On Demand Authorization Failed: ", err);
    }
};

export const createFundingSource = async (
    options: CreateFundingSourceOptions
) => {
    try {
        return await dwollaClient
            .post(`customers/${options.customerId}/funding-sources`, {
                name: options.fundingSourceName,
                plaidToken: options.plaidToken,
            })
            .then((res) => res.headers.get("location"));
    } catch (err) {
        console.error("Creating a Funding Source Failed: ", err);
    }
};

export const addFundingSource = async ({
                                           dwollaCustomerId,
                                           processorToken,
                                           bankName,
                                       }: AddFundingSourceParams) => {
    try {
        // create dwolla auth link
        const dwollaAuthLinks = await createOnDemandAuthorization();

        // add funding source to the dwolla customer & get the funding source url
        const fundingSourceOptions = {
            customerId: dwollaCustomerId,
            fundingSourceName: bankName,
            plaidToken: processorToken,
            _links: dwollaAuthLinks,
        };
        return await createFundingSource(fundingSourceOptions);
    } catch (err) {
        console.error("Transfer fund failed: ", err);
    }
};


